package tnviet.proj.jna.utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * Usage of following class can go as ...
 * <P><PRE><CODE>
 * 		SysCommandExecutor cmdExecutor = new SysCommandExecutor();
 * 		cmdExecutor.setOutputLogDevice(new LogDevice());
 * 		cmdExecutor.setErrorLogDevice(new LogDevice());
 * 		int exitStatus = cmdExecutor.runCommand(commandLine);
 * </CODE></PRE></P>
 *
 * OR
 *
 * <P><PRE><CODE>
 * 		SysCommandExecutor cmdExecutor = new SysCommandExecutor();
 * 		int exitStatus = cmdExecutor.runCommand(commandLine);
 *
 * 		String cmdError = cmdExecutor.getCommandError();
 * 		String cmdOutput = cmdExecutor.getCommandOutput();
 * </CODE></PRE></P>
 */
public class SysCommandExecutor
{
	private String fWorkingDirectory = null;
	private List fEnvironmentVarList = null;




	public void setWorkingDirectory(String workingDirectory) {
		fWorkingDirectory = workingDirectory;
	}

	public void setEnvironmentVar(String name, String value)
	{
		if( fEnvironmentVarList == null )
			fEnvironmentVarList = new ArrayList();

		fEnvironmentVarList.add(new EnvironmentVar(name, value));
	}



	public int runCommand(String commandLine) throws Exception
	{
		/* run command */
		Process process = runCommandHelper(commandLine);

		/* start output and error read threads */

		/* wait for command execution to terminate */
		int exitStatus = -1;
		try {
			exitStatus = process.waitFor();

		} catch (Throwable ex) {
			throw new Exception(ex.getMessage());

		} 
		return exitStatus;
	}

	private Process runCommandHelper(String commandLine) throws IOException
	{
		Process process = null;
		if( fWorkingDirectory == null )
			process = Runtime.getRuntime().exec(commandLine, getEnvTokens());
		else
			process = Runtime.getRuntime().exec(commandLine, getEnvTokens(), new File(fWorkingDirectory));

		return process;
	}

	

	private String[] getEnvTokens()
	{
		if( fEnvironmentVarList == null )
			return null;

		String[] envTokenArray = new String[fEnvironmentVarList.size()];
		Iterator envVarIter = fEnvironmentVarList.iterator();
		int nEnvVarIndex = 0;
		while (envVarIter.hasNext() == true)
		{
			EnvironmentVar envVar = (EnvironmentVar)(envVarIter.next());
			String envVarToken = envVar.fName + "=" + envVar.fValue;
			envTokenArray[nEnvVarIndex++] = envVarToken;
		}

		return envTokenArray;
	}
}


class EnvironmentVar
{
	public String fName = null;
	public String fValue = null;

	public EnvironmentVar(String name, String value)
	{
		fName = name;
		fValue = value;
	}
}


